<template>
  <div>
    <el-row :gutter="20">
      <el-col :span="8">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="8"><span class="el-custom-title">动作组管理</span></el-col>
            <el-col :span="16" style="float: right">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreate"
                  >添加</el-button
                >
                <el-button type="primary"
                 icon="el-icon-edit"
                 size="mini" @click="handleUpdate()">
                  编辑
                </el-button>
                <el-button
                  size="mini"
                  type="danger"
                   icon="el-icon-delete"
                  @click="ui_delete(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-table
              v-loading="listLoading"
              :data="list"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @row-click="rowClick"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>

              <el-table-column align="center" label="动作组编号" width="95">
                <template slot-scope="scope">
                  {{ scope.row.actionsetNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="动作组名称"
                width="95"
                style="display: none"
              >
                <template slot-scope="scope">
                  {{ scope.row.actionsetName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="备注"
                width="95"
                style="display: none"
              >
                <template slot-scope="scope">
                  {{ scope.row.comment }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="app-container">
          <el-row class="relationContainer">
            <el-col :span="8"><span class="el-custom-title">动作管理</span></el-col>
            <el-col :span="16" style="float:right;">
              <el-button-group style="float: right">
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  class="el-button--mini"
                  @click="handleCreateSon"
                  >添加</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="handleUpdateSon()"
                >
                  编辑
                </el-button>
                <el-button
                  size="mini"
                   icon="el-icon-delete"
                  type="danger"
                  @click="ui_deleteSon(null, null)"
                >
                  删除
                </el-button>
              </el-button-group>
            </el-col>
          </el-row>
          <el-row type="flex" justify="start">
            <el-table
              ref="son"
              v-loading="listLoading"
              :data="list2"
              element-loading-text="Loading"
              border
              fit
              highlight-current-row
              @selection-change="handleSelectionChangeSon"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column
                align="center"
                label="序号"
                width="95"
                v-if="false"
              >
                <template slot-scope="scope">
                  {{ scope.row.id }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="动作编号"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.basicActionNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="编号名称"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.basicActionName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="动作组"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.actionsetName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="动作类型"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.basicActionTypeNo }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="动作类型"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.basicActionTypeName }}
                </template>
              </el-table-column>
              <el-table-column
                align="center"
                label="备注"
                width="95"
                style="display:none;"
              >
                <template slot-scope="scope">
                  {{ scope.row.comment }}
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row>
            <pagination
              v-show="total2 > 0"
              :total="total2"
              :page.sync="listQuery2.page"
              :limit.sync="listQuery2.limit"
              :page-sizes="listQuery2.pageSizes"
              @pagination="fetchDataSon"
            />
          </el-row>
        </div>
      </el-col>
    </el-row>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="动作组编号" prop="actionsetNo">
          <el-input v-model="temp.actionsetNo" />
        </el-form-item>
        <el-form-item label="动作组名称" prop="actionsetName">
          <el-input v-model="temp.actionsetName" />
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="temp.comment" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? ui_create() : ui_update()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="textMap[dialogStatusSon]"
      :visible.sync="dialogFormVisibleSon"
    >
      <el-form
        ref="dataFormson"
        :rules="rulesson"
        :model="tempson"
        label-position="left"
        label-width="120px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="动作编号" prop="basicActionNo">
          <el-input v-model="tempson.basicActionNo" />
        </el-form-item>
        <el-form-item label="编号名称" prop="basicActionName">
          <el-input v-model="tempson.basicActionName" />
        </el-form-item>
        <el-form-item label="动作组" prop="basicActionsetId">
          <el-select
            v-model="tempson.basicActionsetId"
            class="filter-item"
            placeholder="请选择动作组"
            @change="handleMainActionsetChange"
          >
            <el-option
              v-for="item in this.ddActionsets"
              :key="item.id"
              :label="item.actionsetName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="动作类型" prop="basicActiontypeId">
          <el-select
            v-model="tempson.basicActiontypeId"
            class="filter-item"
            placeholder="请选择动作类型"
            @change="handleMainTypeChange"
          >
            <el-option
              v-for="itm in this.ddActionTypes"
              :key="itm.id"
              :label="itm.basicActionTypeName"
              :value="itm.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="comment">
          <el-input v-model="tempson.comment" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibleSon = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="
            dialogStatusSon === 'create' ? ui_createSon() : ui_updateSon()
          "
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import request from "@/utils/request";
import {
  getAll,
  getOne,
  create,
  update,
  deleteBatch
} from "@/api/mesActionSet";

import {
  getAllSon,
  listSon,
  createSon,
  updateSon,
  deleteBatchSon
} from "@/api/mesBasicAction";

import {
  getAllParent,
  listParent,
  createParent,
  updateParent,
  deleteBatchParent
} from "@/api/mesBasicActionType";

export default {
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    const validateActionset = (rule, value, callback) => {
      let val = parseInt(value);
      if (val == null || val <= 0) {
        callback(new Error("请选择动作组"));
      } else {
        callback();
      }
    };
    const validateActionType = (rule, value, callback) => {
      let val = parseInt(value);
      if (val == null || val <= 0) {
        callback(new Error("请选择动作类型"));
      } else {
        callback();
      }
    };
    return {
      filterText: "",
      data2: [],
      defaultProps: {
        children: "children",
        label: "MesActionSet"
      },
      list: null,
      list2: null,
      list3: null,
      listLoading: true,
      total2: 0,
      listQuery2: {
        page: 1,
        limit: 6,
        pageSizes: [6, 10, 14]
      },
      currentActionsetId: 0,
      currentActionTypeId: 0,
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "创建"
      },
      rules: {
        actionsetNo: [
          {
            required: true,
            message: "动作组编号不能为空！",
            trigger: "change"
          }
        ],
        actionsetName: [
          {
            required: true,
            message: "动作组名称不能为空！",
            trigger: "change"
          }
        ]
      },
      temp: {
        id: undefined,
        actionsetNo: "",
        actionsetName: "",
        comment: ""
      },
      //表格變量
      lstSelected: [],
      dialogFormVisibleSon: false,
      dialogStatusSon: "",
      rulesson: {
        basicActionNo: [
          {
            required: true,
            message: "动作编号不能为空！",
            trigger: "change"
          }
        ],
        basicActionName: [
          {
            required: true,
            message: "编号名称不能为空！",
            trigger: "change"
          }
        ],
        basicActionsetId: [
          {
            required: true,
            message: "动作组不能为空！",
            trigger: "change",
            validator: validateActionset
          }
        ],
        basicActiontypeId: [
          {
            required: true,
            message: "动作类型不能为空！",
            trigger: "change",
            validator: validateActionType
          }
        ],
        comment: [
          {
            required: false,
            message: "备注不能为空！",
            trigger: "change"
          }
        ]
      },
      tempson: {
        id: undefined,
        basicActionNo: "",
        basicActionName: "",
        basicActionsetId: 0,
        basicActiontypeId: 0,
        comment: ""
      },
      //表格變量
      lstSelectedSon: [],
      ddActionsets: [],
      ddActionTypes: []
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val);
    }
  },
  created() {
    this.fetchData();
    this.fetchDataSon(0);
    this.fetchDataParent();
  },
  methods: {
    handleSelectionChange(val) {
      this.lstSelected = val;
    },
    fetchData() {
      this.listLoading = true;
      let params = {
        name: ""
      };
      getAll(params).then(response => {
        this.list = response.data;
        if (this.list != null && this.list.length > 0) {
          this.list.map(v => {
            this.ddActionsets.push({
              id: v.id,
              actionsetName: v.actionsetName
            });
          });
        }
        this.ddActionsets.splice(0, 0, { id: 0, actionsetName: "请选择" });
        this.listLoading = false;
      });
    },

    rowClick(row, column, event) {
      this.currentActionsetId = row.id;
      this.fetchDataSon();
    },
    ui_create() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.id = 0; //自增
          create(this.temp).then(() => {
            this.list.unshift(this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_update() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          update(this.temp).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id);
            this.list.splice(index, 1, this.temp);
            this.dialogFormVisible = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_delete(row, index) {
      if (this.lstSelected == null || this.lstSelected.length === 0) {
        this.$message.error("请先选择要删除的动作组");
        return;
      }
      let ids = [];
      this.lstSelected.map(function(elm) {
        ids.push(elm.id);
      });
      deleteBatch(ids).then(() => {
        ids.forEach(elm => {
          const index = this.list.findIndex(v => v.id === elm);
          this.list.splice(index, 1);
        });

        this.dialogFormVisible = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        actionsetNo: "",
        actionsetName: "",
        comment: ""
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleUpdate() {
      if (this.lstSelected == null || this.lstSelected.length !== 1) {
        this.$message.error("请先选择一条动作组");
        return;
      }
      this.temp = Object.assign({}, this.lstSelected[0]); // copy obj
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleSelectionChangeSon(val) {
      if (val == null || val.length == 0) return;
      this.lstSelectedSon = val;
      const type = this.list.find(
        v => v.actionsetName === val[0].actionsetName
      );
      if (type != null) {
        this.currentActionsetId = type.id;
      }
      const actionset = this.list3.find(
        v => v.basicActionTypeNo === val[0].basicActionTypeNo
      );
      if (actionset != null) {
        this.currentActionTypeId = actionset.id;
      }
    },
    fetchDataSon() {
      let params = {
        basicActionsetId: this.currentActionsetId,
        page: this.listQuery2.page,
        size: this.listQuery2.limit
      };
      return listSon(params).then(response => {
        this.list2 = response.data.records;
        this.total2 = response.data.total;
        this.listLoading = false;
      });
    },
    resetTempSon() {
      this.tempson = {
        id: undefined,
        basicActionNo: "",
        basicActionName: "",
        basicActionsetId: 0,
        basicActiontypeId: 0,
        comment: ""
      };
    },
    handleCreateSon() {
      this.resetTempSon();
      this.dialogStatusSon = "create";
      this.dialogFormVisibleSon = true;
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate();
      });
    },
    handleUpdateSon() {
      if (this.lstSelectedSon == null || this.lstSelectedSon.length !== 1) {
        this.$message.error("请先选择一条动作组");
        return;
      }
      this.tempson = Object.assign({}, this.lstSelectedSon[0]); // copy obj
      this.tempson.basicActionsetId = this.currentActionsetId;
      this.tempson.basicActiontypeId = this.currentActionTypeId;
      // this.tempson = { ...this.tempson };
      this.dialogStatusSon = "update";
      this.dialogFormVisibleSon = true;
      this.$nextTick(() => {
        this.$refs["dataFormson"].clearValidate();
      });
    },
    ui_createSon() {
      this.$refs["dataFormson"].validate(valid => {
        if (valid) {
          this.tempson.id = 0; //自增
          createSon(this.tempson).then(() => {
            this.fetchDataSon()
            this.dialogFormVisibleSon = false;
            this.$notify({
              title: "Success",
              message: "添加成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_updateSon() {
      this.$refs["dataFormson"].validate(valid => {
        if (valid) {
          updateSon(this.tempson).then(() => {
            console.log(this.tempson);
            this.$refs["son"].clearSelection();
            const index = this.list2.findIndex(v => v.id === this.tempson.id);
           this.fetchDataSon()
            this.dialogFormVisibleSon = false;
            this.$notify({
              title: "Success",
              message: "修改成功！",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    ui_deleteSon(row, index) {
      if (this.lstSelectedSon == null || this.lstSelectedSon.length === 0) {
        this.$message.error("请先选择要删除的ActionTherbligs");
        return;
      }
      let ids = [];
      this.lstSelectedSon.map(function(elm) {
        ids.push(elm.id);
      });
      deleteBatchSon(ids).then(() => {
        ids.forEach(elm => {
          const index = this.list2.findIndex(v => v.id === elm);
          this.list2.splice(index, 1);
        });
        this.dialogFormVisibleSon = false;
        this.$notify({
          title: "Success",
          message: "删除成功！",
          type: "success",
          duration: 2000
        });
      });
    },
    handleMainActionsetChange(val) {
      this.tempson.basicActionsetId = val;
      this.tempson = { ...this.tempson };
    },
    handleMainTypeChange(val) {
      this.tempson.basicActiontypeId = val;
      this.tempson = { ...this.tempson };
    },
    fetchDataParent() {
      this.listLoading = true;
      return getAllParent().then(response => {
        this.list3 = response.data;
        if (this.list3 != null && this.list3.length > 0) {
          this.list3.map(v => {
            this.ddActionTypes.push({
              id: v.id,
              basicActionTypeName: v.basicActionTypeName
            });
          });
        }
        this.ddActionTypes.splice(0, 0, {
          id: 0,
          basicActionTypeName: "请选择"
        });
        // console.log(this.list3);
        this.listLoading = false;
      });
    }
  }
};
</script>
<style>
.el-row {
  margin-bottom: 20px;
  &:last-child {
    margin-bottom: 0;
  }
}
.el-col {
  border-radius: 4px;
}
.bg-purple-dark {
  background: #99a9bf;
}
.bg-purple {
  background: #d3dce6;
}
.bg-purple-light {
  background: #e5e9f2;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}
</style>
